#!/usr/bin/env python
# -*- coding: utf-8 -*-
from src.model.models import Msg
from src.model.models import IdCreate
from google.appengine.ext import db
from datetime import datetime, timedelta
class BaseDao:
	def __init__(self):
		self.table=''
		self.key=''
	def queryOne(self,keyValue):
		obj = db.GqlQuery("SELECT * FROM "+self.table+" where "+self.key+"=:1",keyValue)
		return obj
	def query(self,map):
		sql="SELECT * FROM "+self.table+" where "
		len =1
		i=1
		values=[]
		for key in map:
			str_i=str(i)
			i=i+1
			sql+=key+"=:"+str_i
			values.append(map[key])
		if(len==1):
			obj = db.GqlQuery(sql,values[0])
		if(len==2):
			obj = db.GqlQuery(sql,values[0],values[1])
		if(len==3):
			obj = db.GqlQuery(sql,values[0],values[1],values[2])
		return obj	
	def queryList(self):
		#print 'queryList:'+"SELECT * FROM "+self.table
		list = db.GqlQuery("SELECT * FROM "+self.table)
		return list  
class IdCreateDao:
	
    def getId(self,tblName):
        ids = db.GqlQuery("SELECT * "
                            "FROM IdCreate where tbl_name=:1",tblName)
        if ids.count()==0:
            idC = IdCreate(id=2,tbl_name=tblName)
            idC.put()
            ids = db.GqlQuery("SELECT * "
                            "FROM IdCreate where tbl_name=:1",tblName)
            return 1
        else:
            id_obj = ids.get()
            re_value =  id_obj.id 
            id_obj.id=re_value+1
            id_obj.put()
            return re_value
    
class MsgDao(BaseDao):
	def __init__(self):
		self.table='Msg'
		self.key='key_name'
	def insert(self,msgTitle,msgContent,fromUser,toUser):
		keyName = IdCreateDao().getId("msg_tbl")
		mydate = datetime.utcnow() + timedelta(hours=+8)#北京时间是+8个时区
		m = Msg(content=msgContent,date=mydate, \
                title=msgTitle,fromUser=fromUser,toUser=toUser)
		m.key_name=str(keyName)        
		m.put()
